<template>
    <div :id="elId" style="height:100%;width:100%"></div>
</template>

<script>
var echarts = require('echarts');
import { merge, debounce } from "lodash";
import baseOption from "./option.js";
import chinaJson from "./china.js"
export default {
    name: "Echarts",
    data() {
        return {
            vOption: {
                series: [],
            },
        };
    },
    props: {
        elId: {
            type: String,
            default: function () {
                return (
                    "robotEcharts-" + (new Date().getTime()) + ((Math.random() * 1000).toFixed(0) + "")
                );
            },
        },
        isMap: {
            type: Boolean,
            default: () => {
                return false;
            }
        },
        optionData: Object,

    },
    computed: {
        // 合并配置对象
        option() {
            return merge({}, baseOption, this.vOption, this.optionData);
        },
    },
    created() { },
    mounted() {
        // 实例化echarts对象
        this.$nextTick(() => {
            this.initChart();
        });
    },
    beforeDestroy() {
        if (!this.chart) {
            return;
        }
        this.chart.dispose();
        this.chart = null;
    },
    watch: {
        optionData: {
            deep: true,
            handler: function () {
                this.$nextTick(() => {
                    this.updateOption();
                });
            },
        },
    },
    methods: {
        initChart() {
            if (!document.getElementById(this.elId)) return;
            if (this.isMap) {
                echarts.registerMap('china', chinaJson);
            }
            this.chart = echarts.init(document.getElementById(this.elId));
            this.chart.setOption(this.option, true);
            const that = this;
            window.addEventListener("resize", debounce(() => {    // 引入debounce，防止频繁更改浏览页尺寸出现页面抖动
                if (that.chart) {
                    that.chart.resize();
                }
            }, 100));
            this.chart.on('click', (params) => {
                this.$emit("chartClick", params);
            });
        },
        updateOption() {
            if (this.chart) {
                this.chart.setOption(this.option, true);
            }
        },
    },
};
</script>
